package com.example.travel_front.Adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.travel_front.Activity.NewsDetailActivity;
import com.example.travel_front.Model.News;
import com.example.travel_front.R;

import java.util.List;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {

    private final List<News> newsList;

    private final Context context;

    public NewsAdapter(List<News> newsList,Context context) {
        this.newsList = newsList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        News news = newsList.get(position);
        holder.title.setText(news.getTitle());
        holder.time.setText(news.getTime());
        holder.place.setText(news.getPlace());
        Glide.with(holder.itemView.getContext()).load(news.getImageUrl()).error(R.drawable.news).into(holder.image);
        // 绑定数据到视图
        holder.itemView.setOnClickListener(v -> {
            // 处理点击事件
            Intent intent = new Intent(context, NewsDetailActivity.class);
            // 可以传递数据
            intent.putExtra("newsId", news.getId());
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return newsList != null ? newsList.size() : 0;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        TextView place;
        TextView time;
        ImageView image;

        public ViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.txtNewsTitle);
            place = itemView.findViewById(R.id.txtNewsPlace);
            time = itemView.findViewById(R.id.txtNewsTime);
            image = itemView.findViewById(R.id.imgNews);
        }
    }
}
